import pinia from '@/stores'
import {defineStore} from 'pinia'
import type {returnToken,loginMess,returnUserInfoData} from '@/api/userInfo'
import userInfoApi from '@/api/userInfo'
import router from '@/router'
import cloneDeep from 'lodash/cloneDeep'
import type { RouteRecordRaw } from 'vue-router';
import {staticRoutes,allAsyncRoutes, anyRoutes} from '@/router/routes'
// 限定userInfo类型
type userInfoStateLimit = {
  token:string,
  userInfo:returnUserInfoData,
  menuRoutes:  RouteRecordRaw[]
}

// 过滤异步路由
function filterAllAsyncRoutes(allAsyncRoutes:RouteRecordRaw[],asyncRoutesName:string[]){
  let asyncRoutes = allAsyncRoutes.filter(item=>{
    if(asyncRoutesName.includes(item.name as string)){
      if(item.children&&item.children.length){
        item.children = filterAllAsyncRoutes(item.children,asyncRoutesName)
      }
      return true
    }
  })
  return asyncRoutes
}

// 便利添加路由
function addRoutes(asyncRoutesAndAny:RouteRecordRaw[]){
  asyncRoutesAndAny.forEach(item=>{
    router.addRoute(item)
  })
}

// 清空异步路由
function removeRoutes(){
  let AllRoutes = router.getRoutes()
  AllRoutes.forEach(item=>{
    router.removeRoute(item.name as string)
  })
  addRoutes(staticRoutes)
}

export const useUserInfoStore = defineStore('userInfo',{
  state:():userInfoStateLimit=>{
    return {
      token:localStorage.getItem('token_key') || '',
      userInfo:{
        routes:[],
        buttons:[],
        roles:[],
        name:'',
        avatar:''
      },
      menuRoutes:staticRoutes
    }
  },
  actions:{
    async login(requiredLogin:loginMess){
      try{
        const result = await userInfoApi.loginUser(requiredLogin)
        this.token = result.token
        localStorage.setItem('token_key',result.token)
        return 'ok'
      } catch(error){
        return Promise.reject('登录失败')
      }
    },
    async getUserInfoMes(){
      try{
        // 存储用户信息
        const result = await userInfoApi.getUserMessage()
        this.userInfo = result
        // 获取信息后，过滤出自己的路由并便利添加
        let asyncRoutesName = result.routes
        // 调用异步函数，过滤路由
        let useAsyncRoutes = filterAllAsyncRoutes(cloneDeep(allAsyncRoutes),asyncRoutesName)
        addRoutes(useAsyncRoutes.concat(anyRoutes))
        // 美誉最后异步无法显示，要给state中的菜单赋值
        this.menuRoutes = staticRoutes.concat(useAsyncRoutes,anyRoutes)
        return 'ok'
      } catch(error){
        return Promise.reject('获取用户信息失败')
      }
    },
    // 清空数据
    async reset(){
      this.token = '',
      localStorage.removeItem('token_key'),
      Object.assign(this.userInfo,{
        routes:[],
        buttons:[],
        roles:[],
        name:'',
        avatar:''})
      // this.userInfo = {}
    },
    async logout(){
      try{
        await userInfoApi.logoutUser()
        // 清空异步路由
        removeRoutes()
        // 退出清空数据
        this.reset()
        return 'ok'
      } catch(error){
        return Promise.reject('退出登录失败')
      }
    }
  },
  getters:{}
})
